from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
from . viewsIndex import upload,limit
from web.settings import BASE_DIR
import os


def goodsadd(request):
    cates = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')

    return render(request,'myadmin/goods/add.html',{'info':cates})

def goodsinsert(request):
    # 获取用户数据
    data=request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    ob=models.Goods()
    ob.title=data['title']
    ob.gnum=int(data['gnum'])
    ob.price=float(data['price'])
    ob.info=data['info']

    ob.cateid=models.Cates.objects.get(id=data['fname'])
    myfile=request.FILES.get('pic_url')
    if myfile:
        ob.pic_url=upload(myfile)
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_list')+'"</script>')
    else:
        return HttpResponse('<script>alert("必须选择商品图片");history.back(-1)</script>')

def goodslist(request):
    ob=models.Goods.objects.all().exclude(status=2)
    types=request.GET.get('types')
    keywords=request.GET.get('keywords')

    if types and keywords:
        if types=='title':
            ob=ob.filter(title__contains=keywords)
        if types=='price':
            ob=ob.filter(price__contains=keywords)
    # 调用 分页
    return limit(request,ob,5,'myadmin/goods/userlist.html')

def goodsre(request):
    gid=request.GET.get('id')
    ob=models.Goods.objects.get(id=gid)
    if request.method=='GET':
        cates = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        return render(request,'myadmin/goods/re.html',{'info':ob,'cates':cates})
    elif request.method=='POST':
        data=request.POST.dict()
        ob.title=data['title']
        ob.price=data['price']
        ob.gnum=data['gnum']
        ob.status=data['status']
        ob.info=data['info']
        ob.cates=models.Cates.objects.get(id=data['fname'])

        myfile=request.FILES.get('pic_url')
        if myfile:
            os.remove(BASE_DIR+ob.pic_url)
            ob.pic_url=upload(myfile)
        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_goods_list')+'"</script>')

def goodsdell(request):
    pid=request.GET.get('id')
    ob=models.Goods.objects.get(id=pid)
    ob.status=2
    ob.save()
    return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goods_list')+'"</script>')